;
(function (window, angular) {
    'use strict';
    angular.module("YB.Widget", ['ngFileUpload'])
        .constant("MESG_TYPE", {Error: 0, Warn: 1, Success: 2, Note: 3, Ask: 4, Invalid: 5, NoAddress: 6})
        .constant("OPERATE_TYPE", {
            Submit: 0,
            Pass: 1,
            Deliver: 2,
            Receive: 3,
            Refuse: 4,
            Invalid: 5,
            Cash: 6,
            Open: 7,
            Close: 8,
            Remit: 9
        })
        .service("ybWidget", ["$q", "$modal", '$log', 'securityRetryQueue', "toaster", "MESG_TYPE", "$filter","ybHttp", function ($q, $modal, $log, queue, toaster, MESG_TYPE, $filter,ybHttp) {

            var fnShowMessage = function (content, type, config, okName) {
                var dft = {
                    Type: MESG_TYPE.Error,
                    OkName: "确定",
                    NoName: "取消",
                    Content: {
                        message: "出错啦！",
                        code: ""
                    }
                };

                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    keyboard: false,
                    templateUrl: 'widget/modal/message.html',
                    controller: 'MessageCtrl',
                    resolve: {
                        settings: function () {
                            angular.extend(dft, config);
                            if (!!content) {
                                if (angular.isString(content)) {
                                    dft.Content.message = content;
                                } else {
                                    dft.Content = content;
                                }
                            }
                            if (!!type) {
                                dft.Type = type;
                            }
                            if (!!okName) {
                                dft.OkName = okName;
                            }
                            return dft;
                        }
                    }
                });
                return instance.result;
            };

            var fnShowToaster = function (type, title, text) {
                toaster.pop({
                    type: type,
                    title: title,
                    body: text,
                    showCloseButton: false,
                    timeout: 2000
                });
            };
            //xbt
            function fnCheckDate(timeStart, timeEnd) {
                var timeObj = {
                    tStart: null,
                    tEnd: null
                };
                if ((angular.isUndefined(timeStart) || !timeStart) && (angular.isUndefined(timeEnd) || !timeEnd)) {
                    return;
                }
                if (!!timeStart && (angular.isUndefined(timeEnd) || !timeEnd)) {
                    timeObj.tStart = fnFormatStartDate(timeStart);
                    return timeObj;
                }
                if ((angular.isUndefined(timeStart) || !timeStart) && !!timeEnd) {
                    timeObj.tEnd = fnFormatEndDate(timeEnd);
                    return timeObj;
                }
                var tmpTime = timeStart;
                if (timeEnd < timeStart) {
                    timeObj.tStart = fnFormatStartDate(timeEnd);
                    timeObj.tEnd = fnFormatEndDate(tmpTime);
                } else {
                    timeObj.tStart = fnFormatStartDate(timeStart);
                    timeObj.tEnd = fnFormatEndDate(timeEnd);
                }
                return timeObj;
            }
            var fnShowLoginModal = function () {
                var instance = $modal.open({
                    animation: true,
                    templateUrl: 'widget/modal/login.html',
                    controller: 'LoginCtrl',
                    backdrop: "static",
                    keyboard: false
                });
                instance.result.then(function (name) {
                        queue.retryAll();
                    },
                    function (reason) {
                        $log.log(reason);
                    })
            };

            var fnRemarkMsg = function (type) {
                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    templateUrl: 'widget/modal/remark.html',
                    controller: 'RemarkMsgCtrl',
                    resolve: {
                        setting: function () {
                            return type;
                        }
                    }
                });
                return instance.result;
            };
            var fnToSort = function (config, index) {
                for (var i = 0, len = config.length; i < len; i++) {
                    if (i != index) {
                        config[i].sortType = "";
                    }
                }
                if (config[index].sortType === "asc") {
                    config[index].sortType = "desc";
                } else {
                    config[index].sortType = "asc";
                }
                return config[index].sortType;
            };

            var fnGetDictionaryMap = function (dictCode) {
                return ybHttp.Post('device','/dataDictionary/searchList',{parentCode: dictCode});
            };

            function fnPlus(arg1, arg2) {
                var r1, r2, m;
                try {
                    r1 = arg1.toString().split(".")[1].length
                } catch (e) {
                    r1 = 0
                }
                try {
                    r2 = arg2.toString().split(".")[1].length
                } catch (e) {
                    r2 = 0
                }
                m = Math.pow(10, Math.max(r1, r2));
                return (arg1 * m + arg2 * m) / m
            }

            function fnMinus(val1, val2) {
                var r1, r2, m, n;
                try {
                    r1 = val1.toString().split(".")[1].length;
                } catch (e) {
                    r1 = 0
                }
                try {
                    r2 = val2.toString().split(".")[1].length;
                } catch (e) {
                    r2 = 0
                }
                m = Math.pow(10, Math.max(r1, r2));
                n = (r1 >= r2) ? r1 : r2;
                return ((val1 * m - val2 * m) / m).toFixed(n);
            }

            function fnTimes(arg1, arg2) {
                var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
                try {
                    m += s1.split(".")[1].length
                } catch (e) {
                }
                try {
                    m += s2.split(".")[1].length
                } catch (e) {
                }
                return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
            }

            function fnDivide(arg1, arg2) {
                var t1 = 0, t2 = 0, r1, r2;
                try {
                    t1 = arg1.toString().split(".")[1].length
                } catch (e) {
                }
                try {
                    t2 = arg2.toString().split(".")[1].length
                } catch (e) {
                }
                r1 = Number(arg1.toString().replace(".", ""));
                r2 = Number(arg2.toString().replace(".", ""));
                return fnAccMul((r1 / r2), Math.pow(10, t2 - t1));
            }

            var fnDataSelector = function (data) {
                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    templateUrl: 'widget/modal/dataSelector.html',
                    controller: 'DataSelectorCtrl',
                    resolve: {
                        settings: function () {
                            return data;
                        }
                    }
                });
                return instance.result;
            };

            window.ybWidget = window.ybWidget || {};

            return {
                ShowMessage: fnShowMessage,
                ShowToaster: fnShowToaster,
                ShowLoginModal: fnShowLoginModal,
                RemarkMsg: fnRemarkMsg,
                ToSort: fnToSort,
                CheckDate: fnCheckDate, //xbt
                GetDictionaryMap: fnGetDictionaryMap,
                Plus: fnPlus,
                Minus: fnMinus,
                Times: fnTimes,
                Divide: fnDivide,
                DataSelector: fnDataSelector,
            };
        }])
        .controller("MessageCtrl", ['$scope', '$modalInstance', 'settings', 'MESG_TYPE', function ($scope, $modalInstance, settings, MESG_TYPE) {
            $scope.settings = settings;
            $scope.selectTable = {};
            // 按照Value的数据类型判断显示不同的表格样式
            if (angular.isArray($scope.settings.Content.Value)) {
                if (angular.isArray($scope.settings.Content.Value[0].Value)) {//自动出入库时使用
                    $scope.selectTable.tableType = 2;
                    if ($scope.settings.Content.Value.length < $scope.settings.Content.Value[0].Value[0].BillInCount && $scope.settings.Content.Value[0].Value[0].ValueType == 1001) {
                        $scope.selectTable.showInfo = 1;
                    }
                    if ($scope.settings.Content.Value.length < $scope.settings.Content.Value[0].Value[0].BillInCount && $scope.settings.Content.Value[0].Value[0].ValueType == 1002) {
                        $scope.selectTable.showInfo = 2;
                    }
                } else {
                    $scope.selectTable.tableType = 1;
                }
            }
            $scope.Type = MESG_TYPE;

            $scope.ok = function () {
                $modalInstance.close("ok");
            };
            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };

        }])

        .controller("LoginCtrl", ['$scope', '$modalInstance', '$window', 'UserContextService', 'ybConfig', 'ybHttp', function ($scope, $modalInstance, $window, UserContextService, ybConfig, ybHttp) {
            $scope.user = {loginName: "", password: "", code: ""};
            $scope.failLogin = false;
            $scope.submitted = false;
            $scope.codeImg = '';
            var authId = '';

            function getAuthCode() {
                var service = "auth";
                var reqUrl = "/auth/authInfo";
                ybHttp.Get(service, reqUrl).then(function (data) {
                    if (data.code != 0) {
                        ybWidget.ShowMessage(data.message);
                        return;
                    }
                    authId = data.value.authId;
                    $scope.codeImg = window.AppData.config.serviceName.auth + '/auth/kaptcha?authid=' + data.value.authId;
                })
            }

            $scope.refresh = function () {
                getAuthCode();
            };
            $scope.login = function (isvalid) {
                if (!isvalid) {
                    $scope.submitted = true;
                    return;
                }
                $scope.submitted = false;
                $scope.user.authId = authId;
                var result = UserContextService.Login($scope.user);
                result.then(function (data) {
                        $scope.failLogin = false;
                        $modalInstance.close(data);

                        $timeout(function () {
                            window.location.reload();
                        });
                    },
                    function (data) {
                        $scope.failLogin = true;
                        $scope.Message = data;
                        $scope.user.Password = "";
                        $scope.user.ValidateCode = "";
                        $scope.refresh();
                    });
            };

            $scope.cancel = function () {
                $modalInstance.dismiss("cancel");
                $window.location.href = ybConfig.getConfig().baseUrl.LoginSite;
            };

            (function () {
                getAuthCode();
            })();
        }])

        .controller("RemarkMsgCtrl", ['$scope', '$modalInstance', 'setting', 'OPERATE_TYPE', function ($scope, $modalInstance, setting, OPERATE_TYPE) {
            $scope.Remark = "";
            function initData() {
                switch (setting) {
                    case OPERATE_TYPE.Submit:
                        $scope.modalName = "提交";
                        break;
                    case OPERATE_TYPE.Pass:
                        $scope.modalName = "通过";
                        break;
                    case OPERATE_TYPE.Deliver:
                        $scope.modalName = "发货";
                        break;
                    case OPERATE_TYPE.Receive:
                        $scope.modalName = "收货";
                        break;
                    case OPERATE_TYPE.Refuse:
                        $scope.modalName = "拒绝";
                        break;
                    case OPERATE_TYPE.Invalid:
                        $scope.modalName = "作废";
                        break;
                    case OPERATE_TYPE.Cash:
                        $scope.modalName = "现金支付";
                        break;
                    case OPERATE_TYPE.Open:
                        $scope.modalName = "激活";
                        break;
                    case OPERATE_TYPE.Close:
                        $scope.modalName = "关闭";
                        break;
                    case OPERATE_TYPE.Remit:
                        $scope.modalName = "汇款支付";
                        break;
                    default:
                        break;
                }
            }

            initData();
            $scope.ok = function (index) {
                $modalInstance.close($scope.Remark);
            };
            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        }])

        .controller("ViewImageCtrl", ['$scope', '$modalInstance', 'settings', function ($scope, $modalInstance, settings) {
            $scope.file = settings;
            $scope.ok = function () {
                $modalInstance.close($scope.selectedList);
            };
        }])

        .controller("DataSelectorCtrl", ['$scope', '$modalInstance', 'ybHttp', 'ybWidget', 'settings', function ($scope, $modalInstance, ybHttp, ybWidget, settings) {
            $scope.condition = {};
            $scope.markInfo = {
                allCheckedData: false,
            };               
            $scope.pageInfo = {
                curPage: 1,
                pageSize: 10,
                pageSizeList: [
                    {
                        code: 10,
                        name: "10/页"
                    },
                    {
                        code: 20,
                        name: "20/页"
                    },
                    {
                        code: 30,
                        name: "30/页"
                    }
                ],
                totalPages: 1,
                totalRows: 0
            };
            $scope.dataList = [];
            $scope.currentType = {
                title: '',

                service: '',
                url: '',
                method: '',

                isNotFilterParam: false, // 为true时，接口所需 页面查询信息不放在filters字段上
                keyWords: [{label: '名称', field: 'name'}], // 组件内页面搜索条件输入框（最多支持两个）
                keyWordsParams: {}, // 组件内页面搜索条件输入框的默认值（key只能是keyWords字段中每项的field）
                otherParams: {}, // 调用该组件时外部传入的非页面可输入的 接口所需参数
                fields: [
                    {
                        name: '序号',
                        dataField: 'index',
                        width: "50%"
                    },
                    {
                        name: '名称',
                        dataField: 'name',
                        width: "50%"
                    }
                ],
                selectedKey: 'id', // 数据是否已被选择的判断字段
                isMultiSelect: false, // 是否支持多选
                isOnlyShow: false, // 是否仅展示信息(为true时，字段isMultiSelect将无效)
            };
            if (!!settings) {
                $scope.modalName = "选择" + settings.title;
                $scope.currentType = settings;

                angular.extend($scope.condition, $scope.currentType.keyWordsParams);
            }

            function getListData(curPage) {
                var service = $scope.currentType.service || 'device';
                var reqUrl = $scope.currentType.url;
                var reqMethod = $scope.currentType.method || 'Post';
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }

                var param = {};
                if ($scope.currentType.isNotFilterParam) {
                    param = angular.copy(angular.extend($scope.condition, $scope.currentType.otherParams));
                } else {
                    param = {
                        filters: angular.copy(angular.extend($scope.condition, $scope.currentType.otherParams))
                    };
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.pageSize = $scope.pageInfo.pageSize;
                ybHttp[reqMethod](service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    if (Array.isArray(resp.value)) {
                        $scope.dataList = resp.value;
                        $scope.pageInfo.totalRows = 1;
                        $scope.pageInfo.totalPages = 1;
                    } else {
                        $scope.dataList = resp.value.list;
                        $scope.pageInfo.totalRows = resp.value.total;
                        $scope.pageInfo.totalPages = resp.value.pages;
                    }
                });
            }

            getListData();

            $scope.search = function (curPage) {
                getListData(curPage);
            };
            $scope.selectItem = function (item) {
                $modalInstance.close(item);
            };

            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };

            $scope.isEventStop = function () {
                if (!!settings.eventStop) {
                    window.event.stopPropagation()
                }
            };

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
            };
            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    $scope.markInfo["allChecked" + type] = checkAll(list);
                }
            };
            function checkAll(list) {
                var selectAllFlag = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAllFlag = false;
                        break;
                    }
                    selectAllFlag = true;
                }
                return selectAllFlag;
            };

            $scope.multiSelectConfirm = function () {
                let arr = $scope.dataList.filter(item => item.isChecked)
                if (arr.length < 1) {
                    ybWidget.ShowToaster('error', '请选择数据');
                    return
                }
                $modalInstance.close(arr);
            };
        }])

    ;
})(window, window.angular);
